package com.fingard.dsp.bank.directbank.ccb02;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.net.FormSubmit;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 建行CCB02电子回单获取
 */
public class CCB02Receipt extends CCB02Base implements IReceipt {
    private static TransIDHelper _idHelper = new TransIDHelper(1, 9999);

    public RetAtsReceipt qryReceipt(final ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptMainDir)) {
            download(p_reqReceipt);
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public void download(ReqQryReceipt p_reqReceipt) {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            int index = 0;//记录上传成功的回单数
            StringBuilder sb = new StringBuilder();
            //返回到ATS的请求String
            StringBuilder json = new StringBuilder();
            if (getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                json.append("tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[");
            } else {
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }
            String uploadType = SmbFileUtil.getUploadType();
            while (tmpIntFrom <= tmpIntTo) {
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, -2);
                //判断是否要重新下载电子回单
                if (tmpCalendarFrom.getTime().before(calendar.getTime())) {
                    if (new File(FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + p_reqReceipt.actNum +
                            File.separator + Format.Date8Format.format(fromDateStep) +
                            File.separator + p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep) + ".txt").exists()) {
                        WriteBankLogLn(FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + p_reqReceipt.actNum + "_"
                                + Format.Date8Format.format(fromDateStep) + ".txt存在，所以账户" + p_reqReceipt.actNum +
                                "在交易日期为" + fromDateStep + "电子回单已下载，无需重复下载，如需再次下载删除本文件即可");
                        continue;
                    }
                }
                int intPageNumber = 1;//页码数 默认查询第一页
                boolean tmpQryNext = true;//异常标志 false表示异常
                boolean tmpPageNext = true;//是否最后一页标志 false表示最后一页
                //当1.1接口异常或1.1接口查询到最后一页时跳出循环
                while (tmpQryNext && tmpPageNext) {
                    //1.1 外联电子回单信息查询
                    //赋值通用参数
                    CCB02Header header = new CCB02Header();
                    header.REQUEST_SN = p_reqReceipt.reqHeader.transSeqID;
                    header.TX_CODE = "NWHD01";//交易码
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, header);
                    xmlWriter.writeStartElement("TX_INFO");
                    xmlWriter.writeElementString("ACC_NO", p_reqReceipt.actNum);
                    xmlWriter.writeElementString("STARTDATE", Format.Date8Format.format(fromDateStep));
                    xmlWriter.writeElementString("ENDDATE", Format.Date8Format.format(fromDateStep));
                    xmlWriter.writeElementString("PAGE", String.valueOf(intPageNumber));
                    xmlWriter.writeElementString("TOTAL_RECORD", getBankConfig().getValueAsString("pageSize"));
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndDocument();

                    String[] tmpStrReq = sendToBank(xmlWriter.toXmlString());

                    if (tmpStrReq[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrReq[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String return_code = tmpBkReader.getFirstText("/TX/RETURN_CODE");//返回码
                            String return_msg = tmpBkReader.getFirstText("/TX/RETURN_MSG");//返回码说明
                            if ("000000".equals(return_code)) {
                                //比较当前页与总页数，判断是否进行下一页操作
                                String page = tmpBkReader.getFirstText("/TX/TX_INFO/PAGE");//当前页
                                String total_page = tmpBkReader.getFirstText("/TX/TX_INFO/TOTAL_PAGE");//总页数
                                if ("0".equals(page) || "0".equals(total_page)) {
                                    tmpQryNext = false;
                                    WriteBankLogLn("外联电子回单信息查询--响应页面为空");
                                    continue;
                                }
                                if (Integer.parseInt(page) == Integer.parseInt(total_page)) {
                                    //当前页=总页数，最后一次循环
                                    tmpPageNext = false;
                                } else {
                                    intPageNumber = Integer.parseInt(page) + 1;
                                }
                                //待下载回单编号
                                //StringBuilder download_nos = new StringBuilder();
                                //循环获取回单编号、获取返回回单信息
                                while (tmpBkReader.read("/TX/TX_INFO/DETAILLIST")) {
                                    //获取返回ATS的回单信息
                                    String brseqNo = tmpBkReader.readedXElement.getSingleText("INNER_NO");//回单编号
                                    String logNO = tmpBkReader.readedXElement.getSingleText("LOG_NO");//交易流水号
                                    String recName = tmpBkReader.readedXElement.getSingleText("OP_ACCT_NAME");//对方账户名
                                    String recAct = tmpBkReader.readedXElement.getSingleText("OP_ACCT_NO");//对方账号
                                    String typ = tmpBkReader.readedXElement.getSingleText("DOC_TYP");//凭证种类
                                    String tranAmt = tmpBkReader.readedXElement.getSingleText("TX_AMT");//交易金额
                                    //String cdFlag=tmpBkReader.readedXElement.getSingleText("CR_COD");//借贷标志
                                    String tranDate = tmpBkReader.readedXElement.getSingleText("TRAN_DATE");//交易日期
                                    String cur = tmpBkReader.readedXElement.getSingleText("CCYCD");//币种
                                    //1.2 外联单笔回单文件查询
                                    String fileName = "";
                                    //赋值通用参数
                                    CCB02Header header1 = new CCB02Header();
                                    header1.REQUEST_SN = p_reqReceipt.reqHeader.transSeqID;
                                    header1.TX_CODE = "NWHD02";
                                    XmlTextWriter queryXmlWriter = new XmlTextWriter();//发银行报文的XML对象
                                    //写入通用的头部节点
                                    writeCommonHeader(queryXmlWriter, header1);
                                    queryXmlWriter.writeStartElement("TX_INFO");
                                    queryXmlWriter.writeElementString("ACC_NO", p_reqReceipt.actNum);//帐号
                                    queryXmlWriter.writeElementString("DOWNLOAD_NOS", brseqNo);//待下载的回单编号
                                    //queryXmlWriter.writeElementString("TRAN_DATE", tranDate);//交易日期
                                    queryXmlWriter.writeEndElement();
                                    queryXmlWriter.writeEndDocument();

                                    //发送外联单笔回单文件查询
                                    String[] tmpStrReq2 = sendToBank(queryXmlWriter.toXmlString());

                                    if (tmpStrReq2[0].length() == 0) {
                                        StringBuilder tmpSbMsg2 = new StringBuilder();
                                        XmlTextReader tmpBkReader2 = loadBankRespXmlReader(tmpStrReq2[1], tmpSbMsg2);
                                        if (tmpBkReader2 != null) {
                                            String returnCode = tmpBkReader2.getFirstText("/TX/RETURN_CODE");//返回码
                                            String returnMsg = tmpBkReader2.getFirstText("/TX/RETURN_MSG");//返回码说明
                                            if ("000000".equals(returnCode)) {
                                                String fileSuccess = tmpBkReader2.getFirstText("/TX/TX_INFO/FILE_SUCCESS");//文件发送成功标志
                                                if ("0".equals(fileSuccess)) {
                                                    fileName = tmpBkReader2.getFirstText("/TX/TX_INFO/FILE_NAME");//文件名
                                                } else {
                                                    WriteBankLogLn("外联批量回单文件查询--文件发送失败");
                                                    continue;
                                                }
                                            } else {
                                                WriteBankLogLn(returnMsg);
                                                continue;
                                            }
                                        } else {
                                            WriteBankLogLn(tmpSbMsg2.toString());
                                            continue;
                                        }
                                    } else {
                                        WriteBankLogLn(tmpStrReq2[1]);
                                        continue;
                                    }
                                    //1.3 文件下载
                                    if ("".equals(fileName) || fileName == null) {
                                        WriteBankLogLn("外联批量回单文件查询--响应文件名为空");
                                        continue;
                                    }
                                    //赋值通用参数
                                    CCB02Header header3 = new CCB02Header();
                                    header3.REQUEST_SN = p_reqReceipt.reqHeader.transSeqID;
                                    header3.TX_CODE = "6W0111";
                                    XmlTextWriter downXmlWriter = new XmlTextWriter();//发银行报文的XML对象
                                    //写入通用的头部节点
                                    writeCommonHeader(downXmlWriter, header3);
                                    downXmlWriter.writeStartElement("TX_INFO");
                                    downXmlWriter.writeElementString("SOURCE", fileName);
                                    downXmlWriter.writeElementString("FILEPATH", "CCMSHD");
                                    downXmlWriter.writeElementString("LOCAL_REMOTE", "0");
                                    downXmlWriter.writeEndElement();
                                    downXmlWriter.writeEndDocument();

                                    //发送文件下载请求报文
                                    String[] tmpStrReq3 = sendToBank(downXmlWriter.toXmlString());

                                    if (tmpStrReq3[0].length() == 0) {
                                        StringBuilder tmpSbMsg3 = new StringBuilder();
                                        XmlTextReader tmpBkReader3 = loadBankRespXmlReader(tmpStrReq3[1], tmpSbMsg3);
                                        if (tmpBkReader3 != null) {
                                            String downReturnCode = tmpBkReader3.getFirstText("/TX/RETURN_CODE");//返回码
                                            String downReturnMsg = tmpBkReader3.getFirstText("/TX/RETURN_MSG");//返回码说明
                                            if ("000000".equals(downReturnCode)) {
                                                retAts.respCode = "0";

                                                //下载成功，取目录对应文件
                                                String download = StringHelper.trimEnd(bankFront.bankReceiptMainDir, "/") + File.separator;
                                                File receiptDir = new File(download + File.separator + fileName);
                                                if (!receiptDir.exists()) {
                                                    WriteBankLogLn("不存在回单目录:" + receiptDir.getName());
                                                    continue;
                                                }
                                                String receiptUploadShared = this.getBankConfig().getValueAsString("receiptUploadShared");
                                                if (StringHelper.isNullOrEmpty(receiptUploadShared) || "false".equalsIgnoreCase(receiptUploadShared)) {
                                                    String newFilePath = Format.Date8Format.format(new Date());
                                                    newFilePath = newFilePath.substring(0, 6) + "/" + newFilePath.substring(6, 8) + "/" + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                                    //for(File file:receiptDir.listFiles()){
                                                    int result = -1;
                                                    String AtsFilePath = "";
                                                    String ftpFilePath = "";
                                                    if (fileName.contains(".pdf")) {
                                                        if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                                            if ("smb".equals(uploadType)) {
                                                                WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                                result = SmbFileUtil.smbUploading(receiptDir.getPath(), newFilePath, FGBiz.dspCenter.dspSet.receiptShareDir);
                                                                AtsFilePath = newFilePath + receiptDir.getName();
                                                            } else if ("localhost".equals(uploadType)) {
                                                                String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                                WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                                result = FileHelper.copyFile(receiptDir.getPath(), shareDir + newFilePath + receiptDir.getName());
                                                                AtsFilePath = newFilePath + receiptDir.getName();
                                                            } else {
                                                                newFilePath = newFilePath.replaceAll(reqHeader.bankCode + "/", "");
                                                                WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                                Map<String, String> map = FormSubmit.fileUpload(FGBiz.dspCenter.dspSet.receiptShareDir, p_reqReceipt.actNum, receiptDir.getPath(), newFilePath, fileName, getCharset());
                                                                WriteBankLogStep3(JSON.toJSONString(map));
                                                                if (map.keySet().size() != 0) {
                                                                    result = Integer.valueOf(map.get("respCode"));
                                                                    newFilePath = map.get("remotePath");
                                                                    AtsFilePath = newFilePath;
                                                                } else {
                                                                    result = -1;
                                                                }
                                                            }

                                                        } else {
                                                            //ftp服务器
                                                            FtpSet ftpSet = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                            WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet.upDir);
                                                            //上传ftp服务器的地址
                                                            AtsFilePath = newFilePath + receiptDir.getName();
                                                            ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" + AtsFilePath;
                                                            WriteBankLogLn("开始将回单" + receiptDir.getPath() + "上传至" + ftpFilePath);
                                                            //上传至ftp
                                                            result = FtpUtil.ftpUploading(ftpSet, receiptDir.getPath(), ftpFilePath);
                                                        }
                                                    } else {
                                                        result = -1;
                                                        WriteBankLogLn("文件" + receiptDir.getPath() + "格式异常");
                                                    }
                                                    if (result == 0 || result == 1) {
                                                        if (result == 0) {
                                                            WriteBankLogLn("文件上传成功");
                                                        } else {
                                                            WriteBankLogLn("文件已存在，不需要重复上传");
                                                        }
                                                        json.append("{");
                                                        json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");//账户
                                                        json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");//币种
                                                        json.append("\"receiptCode\":\"" + brseqNo + "\",");//回单编号
                                                        json.append("\"receiptType\":\"" + "" + "\",");//
                                                        json.append("\"receiptState\":\"" + "" + "\",");//回单状态??
                                                        json.append("\"oppActName\":\"" + recName + "\",");//对方户名
                                                        json.append("\"oppActNum\":\"" + recAct + "\",");//对方账户
                                                        json.append("\"amount\":\"" + tranAmt + "\",");//交易金额
                                                        json.append("\"moneyway\":\"" + "" + "\",");
                                                        if (StringHelper.hasAnyChar(getBankConfig().getValueAsString("limitDateReceipt")) && getBankConfig().getValueAsString("limitDateReceipt").length() == 8) {
                                                            Calendar transDate = Calendar.getInstance();//查询日期
                                                            transDate.setTime(Format.Date8Format.parse(tranDate));
                                                            Calendar limitDate = Calendar.getInstance();//生效日期
                                                            limitDate.setTime(Format.Date8Format.parse(getBankConfig().getValueAsString("limitDateReceipt")));
                                                            if (!transDate.before(limitDate)) {
                                                                json.append("\"tranSeqNo\":\"" + logNO + "\",");//交易流水号，对应明细的交易流水号
                                                            } else {
                                                                json.append("\"tranSeqNo\":\"" + reqHeader.transSeqID + "\",");//
                                                            }
                                                        } else {
                                                            json.append("\"tranSeqNo\":\"" + reqHeader.transSeqID + "\",");//
                                                        }
                                                        json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                                        json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(tranDate)) + "\",");//交易日期
                                                        json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                                        json.append("\"fileType\":\"1\"");
                                                        json.append("},");
                                                        //文件处理完毕，删除临时文件
                                                        File file = new File(receiptDir.getPath());
                                                        if (FileHelper.deleteFileIfExists(file.getPath())) {
                                                            WriteBankLogLn("已删除临时文件：" + file.getPath());
                                                        }
                                                        index++;//上传回单成功数+1
                                                        sb.append(fileName + ",");
                                                    } else {
                                                        WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                                        continue;
                                                    }
                                                } else {
                                                    //保险
                                                    WriteBankLogLn("处理前回单编号:" + logNO);
                                                    logNO = antiTransferStr(logNO);
                                                    WriteBankLogLn("处理后回单编号:" + logNO);
                                                    String targetDir = StringHelper.getDirPathUsingSplitGiveUpLastOne(logNO, 3);
                                                    String targetPath = FGBiz.dspCenter.dspSet.receiptShareDir + File.separator + "CCB" + File.separator + targetDir + File.separator + logNO + ".pdf";
                                                    WriteBankLogLn("源文件路径:" + receiptDir.getAbsolutePath());
                                                    WriteBankLogLn("目标文件路径:" + targetPath);
                                                    FileHelper.copyFile(receiptDir.getAbsolutePath(), targetPath);
                                                    sb.append(logNO + ".pdf" + ",");
                                                    index++;

                                                    if (new File(targetPath).exists()) {
                                                        WriteBankLogLn("推送共享目录成功.");
                                                        File localReceiptFile = new File(receiptDir.getAbsolutePath());
                                                        if (localReceiptFile.exists()) {
                                                            WriteBankLogLn("开始删除本地文件:" + receiptDir.getAbsolutePath());
                                                            boolean isDeleted = localReceiptFile.delete();
                                                            if (isDeleted) {
                                                                WriteBankLogLn("本地文件:" + receiptDir.getAbsolutePath() + ",删除成功");
                                                            }
                                                        }
                                                    }
                                                }
                                            } else {
                                                WriteBankLogLn(downReturnMsg);
                                                continue;
                                            }
                                        } else {
                                            WriteBankLogLn(tmpSbMsg3.toString());
                                            continue;
                                        }
                                    } else {
                                        WriteBankLogLn(tmpStrReq3[1]);
                                        continue;
                                    }
                                }
                            } else {
                                tmpQryNext = false;
                                WriteBankLogLn(return_msg);
                                continue;
                            }
                        } else {
                            tmpQryNext = false;
                            WriteBankLogLn(tmpSbMsg.toString());
                            continue;
                        }
                    } else {
                        tmpQryNext = false;
                        WriteBankLogLn(tmpStrReq[1]);
                        continue;
                    }
                    //记录已下载的回单信息
                    String filePath = FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + p_reqReceipt.actNum + File.separator + Format.Date8Format.format(fromDateStep) + File.separator;
                    Calendar calendar2 = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.DAY_OF_MONTH, -2);
                    if (Format.Date8Format.parse(Format.Date8Format.format(fromDateStep)).before(calendar2.getTime())) {
                        //FileHelper.writeFile(filePath + p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep) + ".txt", "", getCharset());
                    }
                }
            }
            //返回ATS回单信息
            json.deleteCharAt(json.length() - 1);
            json.append("]}");
            WriteBankLogLn("成功保存了" + index + "个文件,文件名为：" + sb);
            if (index > 0 && json.toString().contains("receiptCode")) {
                String[] data;
                String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                if ("nbGateway".equals(receiptPushType)) {
                    WriteBankLogLn("3.推送给网关的数据" + json.toString());
                    data = FormSubmit.receiptInfoSend(json.toString(), this);
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到网关成功,请查看数据");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到网关成功,请查看数据";
                    } else {
                        WriteBankLogLn("推送数据到网关失败");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到网关失败";
                    }
                } else {
                    WriteBankLogLn("3.推送给ATS的数据" + json.toString());
                    data = sendToATS(json.toString());
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到ATS成功,请查看数据");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    } else {
                        WriteBankLogLn("推送数据到ATS失败");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到ATS失败";
                    }
                }
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeRetToATS();
    }
}
